<?php

namespace Mlym\CodeGeneration\Middleware\Bean;

use EasySwoole\Spl\SplBean;
use Mlym\CodeGeneration\Middleware\Bean\Capability\CapabilityBean;
use Mlym\CodeGeneration\Middleware\Bean\Module\ModuleBean;
use Mlym\CodeGeneration\Middleware\Bean\View\ViewColumnBean;

class MiddlewareBean extends SplBean
{
    protected $module;
    protected $view = [];
    protected $capability;

    protected function initialize(): void
    {
        /**
         * 转换module对象
         */
        $this->setModule(new ModuleBean($this->module));

        foreach ($this->view as &$item) {
            /**
             * 生成ViewColumnBean对象
             */
            $item = new ViewColumnBean($item);

            /**
             * View->module 默认为当前module name
             */
            empty($item->getModule()) && $item->setModule($this->getModule()->getTableName());

        }
    }

    protected function setClassMapping(): array
    {
        return [
            'capability' => CapabilityBean::class
        ];
    }

    /**
     * @return mixed
     */
    public function getModule(): ModuleBean
    {
        return $this->module;
    }

    /**
     * @param mixed $module
     */
    public function setModule($module): void
    {
        $this->module = $module;
    }

    /**
     * @return mixed
     */
    public function getView()
    {
        return $this->view;
    }

    /**
     * @param mixed $view
     */
    public function setView($view): void
    {
        $this->view = $view;
    }

    /**
     * @return mixed
     */
    public function getCapability(): CapabilityBean
    {
        return $this->capability;
    }

    /**
     * @param mixed $capability
     */
    public function setCapability($capability): void
    {
        $this->capability = $capability;
    }

    /**
     * 获取View所有字段，以多模块字段形式返回数据
     */
    public function getViewFields(): string
    {
        $fieldArray = [];
        foreach ($this->view as $viewColumnBean) {
            if ($viewColumnBean instanceof ViewColumnBean) {
                /**
                 * view的模块名称与module的模块名称或别名相同时，省略别名前缀；反之，保留
                 */
                if ($viewColumnBean->getModule() == $this->getModule()->getTableName() || $viewColumnBean->getModule() == $this->getModule()->getAlias() ) {
                    $fieldArray[] = "{$this->getModule()->getAlias()}.{$viewColumnBean->getName()} as \"{$viewColumnBean->getName()}\"";
                } else {
                    $fieldArray[] = "{$viewColumnBean->getModule()}.{$viewColumnBean->getName()} as \"{$viewColumnBean->getModule()}.{$viewColumnBean->getName()}\"";
                }
            }
        }
        return implode(', ', $fieldArray);
    }


}